package com.hko.qrip.service.impl;

import it.sauronsoftware.ftp4j.FTPFile;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;

import com.hko.qrip.bean.AwareAlert;
import com.hko.qrip.dao.AwareDao;
import com.hko.qrip.dao.FtpLogDao;
import com.hko.qrip.manager.FTPManager;
import com.hko.qrip.service.AwareService;
import com.hko.qrip.util.QripJobOptions;

public class AwareServiceImpl implements AwareService {

	private static String TIMEROW = "AWARE ISSUE TIME";
	@Autowired
	private QripJobOptions jobOptions;

	@Autowired
	private AwareDao awareDao;

	@Autowired
	private FtpLogDao ftpLogDao;

	@Override
	public int insertAwareAlert(AwareAlert alert) throws SQLException {
		return awareDao.insertAwareAlert(alert);
	}

	@Override
	public void doSync() throws Exception {
		System.out.println("[INFO] Aware sync service started");

		File[] files = downloadFiles();

		for (File file : files) {
			List<AwareAlert> alerts = getAlertFile(file);
			int changeCount = 0;
			for (AwareAlert alert : alerts) {
				changeCount += insertAwareAlert(alert);
			}

			System.out.println(changeCount + " alerts inserted");
			ftpLogDao.insertTableLog(file.getName(), changeCount, alerts.size(), "");
			file.delete();
		}
		System.out.println("[INFO] Aware sync service ended");
	}

	private File[] downloadFiles() throws Exception {
		FTPManager fm = new FTPManager(jobOptions.getFtpHost(), jobOptions.getFtpUser(), jobOptions.getFtpPassword());
		fm.ftpLogin();
		fm.changeDir(jobOptions.getFtpPath());
		FTPFile[] files = fm.listFiles("aware*");
		for (FTPFile file : files) {
			fm.downloadAndDeleteFile(jobOptions.getLocalFilePath() + file.getName(), file.getName());
			System.out.println("downloaded: " + file.getName());
			ftpLogDao.insertFtpLog(file.getName());
		}
		fm.close();

		File lrDir = new File(jobOptions.getLocalFilePath());
		File[] lrFiles = lrDir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File arg0, String arg1) {
				if (arg1.contains("aware")) {
					return true;
				}
				return false;
			}
		});
		return lrFiles;
	}

	private List<AwareAlert> getAlertFile(File file) throws Exception {
		List<AwareAlert> resultList = new ArrayList<AwareAlert>();

		Scanner fin = new Scanner(file);
		Timestamp lineTs = new Timestamp(0L);
		while (fin.hasNextLine()) {
			String line = fin.nextLine().trim();
			if (line.contains(TIMEROW)) {
				Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(line.substring(17));
				lineTs = new Timestamp(date.getTime());
			} else if (line.split(" ").length == 3 && line.contains("K")) {
				AwareAlert alert = new AwareAlert();
				alert.setDatetime(lineTs);
				alert.setCorridor(line.split(" ")[0]);
				alert.setMagnitude(Integer.parseInt(line.split(" ")[1].replace("K", "").replace("+", "")));
				alert.setLocation(line.split(" ")[2]);
				resultList.add(alert);
			}
		}
		fin.close();

		return resultList;
	}
}
